package com.turing.post.account.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.account.util.MasterAccountTransferDetail;
import com.turing.post.account.util.MasterAccountTransferDetailDao;
import com.turing.post.util.GeneralDao;
import com.turing.post.util.PCPSApplicationException;

@Stateless(mappedName = "account.impl.MasterAccountTransferDetailDaoImpl")
@Remote
@Local
public class MasterAccountTransferDetailDaoImpl implements
		MasterAccountTransferDetailDao {
	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	/**
	 * 插入帐户子系统交易流水记录
	 */
	public void insert(MasterAccountTransferDetail matd)
			throws PCPSApplicationException {
		GeneralDao.insert(_em, matd);
	}

	/**
	 * 计算给定某主帐户ID、某银行帐户ID、交易时间之前最大允许赎回的金额
	 * 
	 * @param masaccno
	 * @param bankaccid
	 * @param tranTime
	 * @return
	 */
	public BigInteger getMaxTheoryRedemp(BigInteger masaccno,
			BigInteger bankaccid, Date tranTime) {
		Query query = _em
				.createNativeQuery("select sum(t.TransferInAmount - t.TransferOutAmount) from MasterAccountTransferDetail t where t.MasterAccNo = ?1 and (t.BankAccountId = ?2 or ?2 is NULL) and t.tranTime <= ?3");
		query.setParameter(1, masaccno);
		query.setParameter(2, bankaccid);
		query.setParameter(3, tranTime);
		BigDecimal maxRedemp=(BigDecimal) query.getSingleResult();
		return maxRedemp==null?BigInteger.ZERO:maxRedemp.toBigInteger();
	}

	/**
	 * 根据流水号检索所有的主帐户转账明细
	 * 
	 * @param accSeqNo
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<MasterAccountTransferDetail> getAllMasterAccountTransferDetailByAccSeqNo(
			String accSeqNo) {
		Query query = _em
				.createNativeQuery(
						"select t.* from MasterAccountTransferDetail t where t.AccSeqNo = ?1",
						MasterAccountTransferDetail.class);
		query.setParameter(1, accSeqNo);
		return query.getResultList();
	}
}